import { MciDrawer } from '@/components/base';
import { InjectionKey, PropType, Suspense } from 'vue';
import { px2Rem, px2RemValue } from '@/utils/rem';

export const useDrawerSize = (calcWidth: number = 0) => {
  const compSize = ref(px2Rem('1360px') as any);

  const calcCompSize = computed(() => {
    const { clientWidth } = document.documentElement;
    if (compSize.size === '90%') {
      return (clientWidth * 0.9 - calcWidth).toFixed(2) + 'px';
    }
    return (px2RemValue(1360) - calcWidth).toFixed(2) + 'px';
  });

  const updateCompSize = () => {
    const { clientWidth } = document.documentElement;

    if (clientWidth >= 1440) {
      compSize.value = px2Rem('1360px');
    } else {
      compSize.value = '90%';
    }
  };

  window.onresize = updateCompSize;

  onMounted(updateCompSize);

  return {
    compSize,
    calcCompSize
  };
};

interface IDrawerRouter {
  setCloseHandle(handle: (doClose: () => void) => Promise<void> | void): void;
}

const drawerRouterKey = 'DrawerRouter' as unknown as InjectionKey<IDrawerRouter>;

/**
 * 设置抽屉关闭按钮事件
 *
 * @example
 *
 * const ctx = useDrawerClose();
 * ctx?.setCloseHandle((continueClose) => {
 *   router.back();
 *   // 继续执行原本关闭事件
 *   continueClose();
 * });
 */
export const useDrawerClose = () => {
  const ctx = inject(drawerRouterKey, null);

  return ctx;
};

export const DrawerRouter = defineComponent({
  name: 'DrawerRouter',
  props: {
    // 显示的规则
    visibleMethod: {
      type: Function as PropType<TAnyFunction<boolean>>,
      default: () => {
        return false;
      }
    },
    // 抽屉大小
    size: {
      type: [String, Number],
      default: ''
    },
    close: {
      type: Function as PropType<IFunction>,
      default: null
    },
    // 修改关闭二次确认校验
    modifyValidator: {
      type: Boolean,
      default: true
    },
    title: {
      type: [String, Object],
      default: ''
    }
  },
  setup(props) {
    const visibleComputed = computed(props.visibleMethod);
    const route = useRoute();
    const router = useRouter();
    let closeHandle: any = null;

    const visible = ref(visibleComputed.value);

    watch(visibleComputed, (val) => {
      if (val !== visible.value) visible.value = val;
    });

    provide(drawerRouterKey, {
      setCloseHandle(handle) {
        closeHandle = handle;
      }
    });

    watch(
      () => route.name,
      () => {
        closeHandle = null;
      }
    );

    const beforeClose = async () => {
      const close = () => {
        if (props.close) {
          props.close();
        } else {
          router.back();
        }
      };
      if (typeof closeHandle === 'function') {
        closeHandle(close);
        return;
      }
      close();
    };
    const realTitle = computed(() => {
      return visible.value ? props.title || route.meta.title + '' : null;
    });

    return {
      realTitle,
      visible,
      beforeClose,
      ...useDrawerSize()
    };
  },
  render() {
    return (
      <MciDrawer
        class="drawer-router"
        title={this.realTitle}
        modelValue={this.visible}
        size={this.size || this.compSize}
        custom-class="drawer-router"
        modify-confirm
        vSlots={this.$slots}
        modifyConfirm={this.modifyValidator}
        beforeClose={this.beforeClose}>
        <Suspense timeout={2000}>
          <router-view />
        </Suspense>
      </MciDrawer>
    );
  }
});
